function ExtraRinex3(filena,OutDir)
%ExtraRinex3 - RINEX3 file extraction from crx.gz file)
%
%       ExtraRinex3(Filena,OutDir)
%
% This function extracts the RINEX3 file from a Hatanaka compressed and 
% gzipped file. For example, if Filena is 
%           'MSEL00ITA_R_20211230000_01D_30S_MO.crx.gz', 
% the output file is 
%           'MSEL00ITA_R_20211230000_01D_30S_MO.rnx'.
%
% Notes about the input arguments:
% - if Filena is undefined or empty, the input .crx.gz filename can be 
%   managed in interactive way;
% - if OutDir is undefined or empty, the current directory is used.
% 
% This function requires these external packages:
%   - RNXCMP (windows10 64 bit or Linux 64 bit placed on c:\GNSS\RNXCMP\bin
%     or /mnt/c/GNSS/RNXCMP/bin/ directory respectively. If a different 
%     version and/or a different folder should be used, the function must 
%     be edited accordingly).
%     Download link: https://terras.gsi.go.jp/ja/crx2rnx.html
%
%       ExtraRinex3(Filena,OutDir)
%
%  See also Rinex32Rinex2, StationNameEdit. 

% G. Teza, 20232

if nargin < 2 || isempty(OutDir)
    OutDir = pwd;
end
if nargin < 1 || isempty(filena)
    [filena, pathna] = uigetfile(...
        {'*.gz','compressed RINEX 3 files (*.crx.gz)'},...
        'INPUT RINEX 3 FILE');
    if ~isequal(filena,0) && ~isequal(pathna,0)
        filena = fullfile(pathna,filena);
    else
        warning('Invalid input file - no conversion');
        return
    end
end

if ispc
    commHata = '"c:\GNSS\RNXCMP\bin\crx2rnx.exe" ';
elseif isunix
    commHata = '/mnt/c/GNSS/RNXCMP/bin/crx2rnx ';
else
    error('Unsuitable operating system');
end

[~,filenam,ext] = fileparts(filena);

% Rinex3 filenames management (WF: with output folder path)
filena3kgz = [filenam ext];
filenaWF3kgz = fullfile(OutDir,filena3kgz);
filenaWF3kcrx = filenaWF3kgz(1:end-3);
filenaWF3krnx = [filenaWF3kcrx(1:end-4) '.rnx'];

% gunzip:
gunzip(filena,OutDir);
delete(filena);

% Hatanaka decompression:
commHatak = [commHata filenaWF3kcrx];
if exist(filenaWF3krnx,'file') % removal of the already decompressed file, if existing
    delete(filenaWF3krnx);
end
system(commHatak);  
delete(filenaWF3kcrx);  % removal of the Hatanaka compressed file